package com.atguigu.tingshu.album.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.mapper.AlbumAttributeValueMapper;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MxwListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AlbumAttributeValueMapper albumAttributeValueMapper;

    @RabbitListener(queues = "test.queue")
    public void mxwListen(String json, Channel channel, Message message) throws IOException {
        if (StringUtils.isBlank(json)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }
        //反序列化
        MxwObject mxwObject = JSON.parseObject(json, MxwObject.class);
        //判断数据库
        if ("tingshu_album".equals(mxwObject.getDatabase())){
            //判断表
            if ("album_info".equals(mxwObject.getTable())){
                AlbumInfo albumInfo = JSON.parseObject(mxwObject.getData(), AlbumInfo.class);
                if ("insert".equals(mxwObject.getType())||"update".equals(mxwObject.getType())){
                    //根据专辑id查询标签信息
                    List<AlbumAttributeValue> albumAttributeValues = this.albumAttributeValueMapper.selectList(new LambdaQueryWrapper<AlbumAttributeValue>().eq(AlbumAttributeValue::getAlbumId, albumInfo.getId()));

                    albumInfo.setAlbumAttributeValueVoList(albumAttributeValues);


                    this.redisTemplate.opsForValue().set(RedisConstant.ALBUM_INFO_PREFIX+albumInfo.getId(),albumInfo,RedisConstant.CACHE_TIMEOUT, TimeUnit.SECONDS);

                }else if ("delete".equals(mxwObject.getType())){
                    this.redisTemplate.delete(RedisConstant.ALBUM_INFO_PREFIX+albumInfo.getId());
                }
            }
            //声音同步

        }else if ("tingshu_user".equals(mxwObject.getDatabase())){

        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        return;
    }

}
